#!/usr/bin/env node

/**
 * 安全检查脚本
 * 检查代码中是否有硬编码的敏感信息
 */

const fs = require('fs');
const path = require('path');

const SENSITIVE_PATTERNS = [
    /sk-[a-zA-Z0-9]{48}/,  // OpenAI API Key pattern
    /gsk_[a-zA-Z0-9]{48}/, // OpenAI API Key pattern (new format)
    /["'](sk-[a-zA-Z0-9]{48})["']/,
    /["'](gsk_[a-zA-Z0-9]{48})["']/,
    /["'][a-f0-9]{32}["']/,  // Possible API keys
    /["'][a-zA-Z0-9]{40,}["']/, // Possible long keys
    /youdao[a-zA-Z0-9]{20,}/i, // Youdao keys
    /appSecret\s*:\s*["'][^"']{10,}["']/i,
    /apiKey\s*:\s*["'][^"']{10,}["']/i,
    /appKey\s*:\s*["'][^"']{10,}["']/i
];

const FILES_TO_CHECK = [
    '*.js',
    '*.json',
    '*.html',
    '*.md'
];

const FILES_TO_EXCLUDE = [
    'node_modules/',
    '.git/',
    'dist/',
    'build/',
    '.gitignore',
    'security-check.js'
];

function findFiles(dir, extensions, exclude) {
    const files = [];

    function traverse(currentDir) {
        const items = fs.readdirSync(currentDir);

        for (const item of items) {
            const fullPath = path.join(currentDir, item);
            const stat = fs.statSync(fullPath);

            // Skip excluded directories
            if (exclude.some(pattern => fullPath.includes(pattern))) {
                continue;
            }

            if (stat.isDirectory()) {
                traverse(fullPath);
            } else if (extensions.some(ext => item.endsWith(ext))) {
                files.push(fullPath);
            }
        }
    }

    traverse(dir);
    return files;
}

function checkFile(filePath) {
    const content = fs.readFileSync(filePath, 'utf8');
    const issues = [];

    SENSITIVE_PATTERNS.forEach((pattern, index) => {
        const matches = content.match(pattern);
        if (matches) {
            issues.push({
                type: 'POTENTIAL_CREDENTIAL',
                pattern: pattern.toString(),
                matches: matches,
                lineNumber: getLineNumber(content, matches[0])
            });
        }
    });

    return issues;
}

function getLineNumber(content, match) {
    const beforeMatch = content.substring(0, content.indexOf(match));
    return beforeMatch.split('\n').length;
}

function main() {
    console.log('🔒 Running security check...\n');

    const files = findFiles('.', FILES_TO_CHECK, FILES_TO_EXCLUDE);
    let totalIssues = 0;

    for (const file of files) {
        const issues = checkFile(file);
        if (issues.length > 0) {
            console.log(`❌ ${file}:`);
            issues.forEach(issue => {
                console.log(`   Line ${issue.lineNumber}: ${issue.matches[0]}`);
                console.log(`   Pattern: ${issue.pattern}`);
            });
            console.log('');
            totalIssues++;
        } else {
            console.log(`✅ ${file}: OK`);
        }
    }

    console.log('\n' + '='.repeat(50));
    if (totalIssues === 0) {
        console.log('✅ Security check passed! No sensitive information found.');
        console.log('🔐 Your API keys are stored safely in Chrome storage (not in code).');
    } else {
        console.log(`❌ Found ${totalIssues} potential security issues.`);
        console.log('🚨 Please remove or replace sensitive information before committing.');
        console.log('');
        console.log('Recommended actions:');
        console.log('1. Replace hard-coded keys with empty strings');
        console.log('2. Use environment variables for development');
        console.log('3. Ensure sensitive data is only stored in Chrome storage');
    }

    process.exit(totalIssues === 0 ? 0 : 1);
}

if (require.main === module) {
    main();
}